package com.wuql.create.dao;

import com.wuql.create.bean.ClassColumn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author : wuQingLiang
 * @date : 2024/3/14
 **/
@Repository
public class ColumnDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     *  查询数据表所有字段的名称、数据类型、注释
     * @param table_schema 数据库名称
     * @param tableName 数据表名称
     * @return
     */
    public List<ClassColumn> queryColumnList(String table_schema,String tableName){
        String sql = "select lower(column_name)as column_name_line, lower(data_type) as data_type,column_comment from information_schema.columns where table_schema = ? and  table_name = ?";
        List<ClassColumn> list = jdbcTemplate.query(sql, new Object[]{table_schema,tableName}, new BeanPropertyRowMapper<ClassColumn>(ClassColumn.class));
        return list;
    }

    /**
     * 查询数据表主键的名称、数据类型、注释
     * @param table_schema 数据库名称
     * @param tableName 数据表名称
     * @return
     */
    public ClassColumn getTableKey(String table_schema,String tableName){
        String sql = "select lower(column_name)as column_name_line, lower(data_type) as data_type,column_comment from information_schema.columns where table_schema = ? and  table_name = ? and  column_key = 'PRI'";
        List<ClassColumn> list = jdbcTemplate.query(sql, new Object[]{table_schema,tableName}, new BeanPropertyRowMapper<ClassColumn>(ClassColumn.class));
        ClassColumn keyColumn=new ClassColumn();
        if(list.size()>0){
            keyColumn=list.get(0);
        }else{
            throw new RuntimeException(tableName+"表没有主键！");
        }
        return keyColumn;
    }
}
